<template>
  <div class="hello">
    <el-row :gutter="20">
      <el-col :span="12">
        <button @click="getAllStudent">刷新列表</button>
        <ul>
          <li v-for="s in studentList" :key="s.id">
            {{s.name}}
            <input type="text" v-model="s.name"/>
            <button v-if="s._isChanged" @click="s.save()">保存</button>
          </li>
        </ul>
        <input type="text" v-model="student.name"/>
        <button @click="addStudent">添加</button>
      </el-col>
      <el-col :span="12"></el-col>
    </el-row>
  </div>
</template>

<script>
import {DexieObject, db} from '@/core/DexieObject.js'

function Student (name) {
  this.name = name
  DexieObject.call(this)
}

Student.prototype = Object.assign(
  Object.create(DexieObject.prototype),
  {
    constructor: Student,
    tableName: 'Student'
  }
)

db.Student.mapToClass(Student)

export default {
  name: 'HelloWorld',
  data () {
    var student = new Student('新学生')
    return {
      student,
      studentList: []
    }
  },
  methods: {
    getAllStudent () {
      db.Student.toArray(students => {
        students.forEach(student => {
          student.init(true)
        })
        this.studentList = students
      })
    },
    addStudent () {
      this.student.save()
      this.student = new Student('新学生')
      this.getAllStudent()
    }
  },
  mounted () {
    this.getAllStudent()
  }
}
</script>

<style scoped></style>
